/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.blogspot.armelnene.gwtopenid.client;

import com.blogspot.armelnene.gwtopenid.client.services.GWTService;
import com.blogspot.armelnene.gwtopenid.client.services.GWTServiceAsync;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Hyperlink;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import java.util.Map;

/**
 * Main entry point.
 *
 * @author Armel
 */
public class openidEntryPoint implements EntryPoint {

    VerticalPanel contentPanel = new VerticalPanel();

    /**
     * Creates a new instance of openidEntryPoint
     */
    public openidEntryPoint() {
    }

    /** 
     * The entry point method, called automatically by loading a module
     * that declares an implementing class as an entry-point
     */
    public void onModuleLoad() {
            setupLoginPanel();
    }

    public static GWTServiceAsync getService() {
        return GWT.create(GWTService.class);
    }

    /**
     *  This method creates a user interface to allow site users to log-in using
     *  their OpenID provider url
     */
    private void setupLoginPanel() {
        final Label sign = new Label("Login with OpenID");
        
        final TextBox openIdUrl = new TextBox();
        openIdUrl.setWidth("250px");
        Button login = new Button("Sign in");
        // the AsynCallback which will be used to communicate between the front-end
        // and server-side
        final UserAsyncCallback callback = new UserAsyncCallback();
        login.addClickHandler(new ClickHandler() {

            public void onClick(ClickEvent event) {
                if (sign.getText() == null || sign.getText().isEmpty()) {
                    return;
                }
                // retrieve the OpenID url from the text field and sends it to the
                // back-end for discovery
                getService().authenticateOpenId(openIdUrl.getText(), callback);
            }
        });

        HorizontalPanel vp = new HorizontalPanel();
        vp.add(openIdUrl);
        vp.add(login);

        Image google = new Image("images/google_logo.png");
        google.setSize("100px", "40px");
        Image myspace = new Image("images/Myspaceid.jpg");
        myspace.setSize("100px", "40px");
        Image aol = new Image("images/aol_logo.png");
        aol.setSize("100px", "40px");
        Image facebook = new Image("images/logo_facebook.jpg");
        facebook.setSize("100px", "40px");
        Image twitter = new Image("images/twitter_logo.jpg");
        twitter.setSize("100px", "40px");
        Image yahoo = new Image("images/yahoo-logo.jpg");
        yahoo.setSize("100px", "40px");

        FlowPanel fpanel = new FlowPanel();
        fpanel.add(google);
        fpanel.add(myspace);
        fpanel.add(aol);
        fpanel.add(facebook);
        fpanel.add(twitter);
        fpanel.add(yahoo);

        Image openid = new Image("images/openid-logo-2.png");
        openid.setSize("28px", "28px");
        HorizontalPanel titlePanel = new HorizontalPanel();
        titlePanel.add(openid);
        titlePanel.add(sign);


        contentPanel.setSize("400px", "350px");
        contentPanel.setSpacing(5);
        contentPanel.add(titlePanel);
        contentPanel.add(vp);
        contentPanel.add(new HTML("<b>We also support the following OpenID providers</b>"));
        contentPanel.add(fpanel);

        // This is where the magic happens - This code is only usefull when the OpenID provider
        // redirects the user back to your site - please visit openid.net for valid parameters.
        // The "if" statement checks to make sure that it is a valid response from the OpenID
        // provider - You can do anything you want with the results here such as verifying the
        // response with the server-side code
        if(Window.Location.getParameter("openid.rpnonce") != null){
            String s = Window.Location.getParameter("openid.mode");
            // executes this if the user cancels the authentication process and the OpenID
            // providers returns to the your site
            if(s.equals("cancel")){
            sign.setText("Server returned openid.mode=cancel");
            openIdUrl.setText("You need to Accept not Cancel");
            }
            // Here, I am assuming that everything is fine and that the user has been sucessfully logged in
            else{
                sign.setText("You have successfully signed in");
                vp.setVisible(false);
            }

        }
        RootPanel.get().add(contentPanel);

    }

    private class UserAsyncCallback implements AsyncCallback<User> {

        public void onFailure(Throwable caught) {
            Window.alert(caught.getLocalizedMessage());
        }

        public void onSuccess(User result) {
            if (result != null) {
//                    Window.open(result.getRedirect(), "_blank", "height=200,width=400,left=100," +
//                            "top=100,resizable=no,scrollbars=no,toolbar=no,status=yes");
                // this the most important line in order to make the authentication. Here, I am redirecting the user
                // from the client side to the OpenID provider URL with the discovery data generated from the
                // RPC call to the servlet.
                Window.Location.assign(result.getRedirect());
            } else {
                Window.alert("Ooops!!! Couldn't find your provider");
            }
        }
    }
}
